<template>
  <div class="users-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input v-model="searchForm.hm" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
              <el-option label="管理员" :value="0" />
              <el-option label="教师" :value="1" />
              <el-option label="学生" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
            <el-button type="success" :icon="Plus" @click="handleAdd">新增用户</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="users" v-loading="loading" style="width: 100%">
        <el-table-column prop="hm" label="用户名" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限描述">
            <template #default="{ row }">
              <span class="text-gray-500">{{ getRoleDescription(row.role) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="360">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleResetPassword(row)" v-if="userStore.user.role === 0">重置密码</el-button>
            <el-button 
              :type="row.status === 1 ? 'info' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)"
              v-if="userStore.user.role === 0 && row.hm !== userStore.user.hm"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)" v-if="row.hm !== userStore.user.hm">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px">
        <el-form-item label="用户名" prop="hm">
          <el-input v-model="userForm.hm" placeholder="请输入用户名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd" v-if="!isEdit">
          <el-input v-model="userForm.pwd" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" :value="0" />
            <el-option label="教师" :value="1" />
            <el-option label="学生" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" v-model="resetPasswordVisible" width="400px">
      <el-form :model="resetPasswordForm" :rules="resetPasswordRules" ref="resetPasswordFormRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="resetPasswordForm.hm" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPasswordSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { userApi } from '@/api'
import { useUserStore } from '@/stores/user'

export default {
  name: 'Users',
  components: {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete
  },
  setup() {
    const userStore = useUserStore()
    return { userStore }
  },
  data() {
    return {
      users: [],
      loading: false,
      searchForm: {
        hm: '',
        role: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      userForm: {
        hm: '',
        pwd: '',
        role: 2,
        status: 1
      },
      userRules: {
        hm: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      resetPasswordVisible: false,
      resetPasswordForm: {
        hm: '',
        newPassword: '',
        confirmPassword: ''
      },
      resetPasswordRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.resetPasswordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },

    }
  },
  async mounted() {
    await this.loadUsers()
  },
  methods: {
    getRoleTagType(roleValue) {
      switch (roleValue) {
        case 0: return 'danger'   // 管理员
        case 1: return 'warning'  // 教师
        case 2: return 'primary'  // 学生
        default: return 'info'
      }
    },
    getRoleText(roleValue) {
      switch (roleValue) {
        case 0: return '管理员'
        case 1: return '教师'
        case 2: return '学生'
        default: return '未知'
      }
    },
    getRoleDescription(roleValue) {
      switch (roleValue) {
        case 0: return '最高权限 - 可管理所有功能'
        case 1: return '教师权限 - 可管理课程和成绩'
        case 2: return '学生权限 - 可查看个人信息'
        default: return '未知权限'
      }
    },
    async loadUsers() {
      try {
        this.loading = true
        const response = await userApi.getAllUsers()
        this.users = response.data || []
      } catch (error) {
        this.$message.error('获取用户列表失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },

    async handleSearch() {
      try {
        this.loading = true
        let response
        
        if (this.searchForm.hm) {
          // 按用户名搜索
          response = await userApi.getUserByHm(this.searchForm.hm)
          this.users = response.data ? [response.data] : []
        } else if (this.searchForm.role !== '') {
          // 按角色搜索
          response = await userApi.getUsersByRole(this.searchForm.role)
          this.users = response.data || []
        } else {
          // 获取所有用户
          await this.loadUsers()
          return
        }
      } catch (error) {
        this.$message.error('搜索失败：' + (error.message || '未知错误'))
        this.users = []
      } finally {
        this.loading = false
      }
    },
    handleReset() {
      this.searchForm = {
        hm: '',
        role: ''
      }
      this.loadUsers()
    },
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.isEdit = false
      this.userForm = {
        hm: '',
        pwd: '',
        role: 2,
        status: 1
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.isEdit = true
      this.userForm = {
        hm: row.hm,
        role: row.role,
        status: row.status || 1
      }
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        try {
          await userApi.deleteUser(row.hm)
          this.$message.success('删除成功')
          await this.loadUsers()
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.userFormRef.validate()
        
        try {
          if (this.isEdit) {
            // 编辑用户
            await userApi.updateUser(this.userForm.hm, {
              role: this.userForm.role
            })
            this.$message.success('更新成功')
          } else {
            // 新增用户
            await userApi.addUser(this.userForm)
            this.$message.success('新增成功')
          }
          this.dialogVisible = false
          await this.loadUsers()
        } catch (error) {
          this.$message.error('操作失败：' + (error.message || '未知错误'))
        }
      } catch (error) {
        this.$message.error('表单验证失败')
      }
    },
    handleCancel() {
      this.dialogVisible = false
    },
    handleResetPassword(row) {
      this.resetPasswordForm = {
        hm: row.hm,
        newPassword: '',
        confirmPassword: ''
      }
      this.resetPasswordVisible = true
    },
    async handleResetPasswordSubmit() {
      try {
        await this.$refs.resetPasswordFormRef.validate()
        
        try {
          await userApi.resetPassword(this.resetPasswordForm.hm, {
            newPassword: this.resetPasswordForm.newPassword
          })
          this.$message.success('密码重置成功')
          this.resetPasswordVisible = false
        } catch (error) {
          this.$message.error('密码重置失败：' + (error.message || '未知错误'))
        }
      } catch (error) {
        this.$message.error('表单验证失败')
      }
    },
    async handleToggleStatus(row) {
      const newStatus = row.status === 1 ? 0 : 1
      const action = newStatus === 1 ? '启用' : '禁用'
      
      this.$confirm(`确定要${action}用户 ${row.hm} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await userApi.toggleUserStatus(row.hm, newStatus)
          this.$message.success(`${action}成功`)
          await this.loadUsers()
        } catch (error) {
          this.$message.error(`${action}失败：` + (error.message || '未知错误'))
        }
      })
    }
  }
}
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>